import asyncio
import os
from typing import Annotated

import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.functions import KernelArguments, kernel_function
from semantic_kernel.prompt_template import PromptTemplateConfig, InputVariable


async def run_function(*args):
   return await kernel.invoke(*args)


if __name__=='__main__':

   os.environ["OPENAI_API_KEY"] = os.environ["OPENAI_API_KEY_ZHIHU"]
   os.environ["OPENAI_BASE_URL"] = os.environ["OPENAI_API_BASE_ZHIHU"]

   translate_prompt = f"""
   将中文词'{{$chinese}}'翻译为日语
   直接给出一个翻译结果，不要评论，
   尽可能用Hanji表示。
   """
   joke_prompt = f"""
   {{$input}}的日语是：{{ChatBotPlugin.translate $input}}
   根据以上词汇在中日文中的差异，讲一个笑话
   """

   serviceId = "translate_service"
   pluginName = "TranslatePlugin"
   translateFunctionName = "translate"
   jokeFunctionName = "koke"

   kernel = sk.Kernel()
   service = OpenAIChatCompletion(ai_model_id="gpt-4o",service_id=serviceId,api_key=os.environ["OPENAI_API_KEY_ZHIHU"])
   kernel.add_service(service)
   #注册 function

   reg_setting = kernel.get_service(service_id=serviceId).get_prompt_execution_settings_class()(service_id = serviceId)

   trans_prompt_template_config = PromptTemplateConfig(name = "translate_config",description="将中文翻译为日语",template=translate_prompt,execution_settings={serviceId:reg_setting},
                                                       input_variables=[InputVariable(name="chinese",description="Chinese source",is_require=True)])

   joke_prompt_template_config = PromptTemplateConfig(name="joke_config", description="讲笑话的函数",template=joke_prompt, execution_settings={serviceId:reg_setting},
                                                       input_variables=[InputVariable(name="input", description="主题",is_require=True)])

   translate_function = kernel.add_function(plugin_name=pluginName,function_name=translateFunctionName,prompt_template_config=trans_prompt_template_config)
   joke_function = kernel.add_function(plugin_name=pluginName,function_name=jokeFunctionName,prompt_template_config=joke_prompt_template_config)

   result = asyncio.run(run_function(joke_function,KernelArguments(input="信件")))
   print(result)